package com.eastedu.superise.handler.question.callback.handler;

import com.eastedu.common.enums.MediaTypeEnum;
import com.eastedu.common.model.question.Fragment;
import com.eastedu.common.model.question.QuestionItemContent;
import com.eastedu.superise.handler.question.handler.ContentConverter;
import com.eastedu.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * The type Stem content rollback converter.
 *
 * @author Administrator
 */
@Slf4j
public class StemContentRollbackConverter implements ContentConverter {

    @Override
    public void convert(List<QuestionItemContent> contents) {
        for (QuestionItemContent itemContent : contents) {
            List<Fragment> newFragments = new ArrayList<>();

            List<Fragment> fragments = itemContent.getFragments();
            log.info("===> 修改前: {}", JsonUtil.toJsonString(fragments));
            Fragment mergeFragment = null;
            for (Fragment fragment : fragments) {
                if (fragment.getMediaType() != MediaTypeEnum.FORMULA) {
                    // 如果mergeFragment不为空，则将其添加到newFragments中, mergeFragment置空
                    if (mergeFragment != null) {
                        newFragments.add(mergeFragment);
                        mergeFragment = null;
                    }
                    newFragments.add(fragment);
                    continue;
                }
                String content = fragment.getContent();
                if (content.startsWith("<math") && content.endsWith("</math>")) {
                    // 如果mergeFragment不为空，则将其添加到newFragments中, mergeFragment置空
                    if (mergeFragment != null) {
                        newFragments.add(mergeFragment);
                        mergeFragment = null;
                    }
                    newFragments.add(fragment);
                    continue;
                }
                // 匹配拆分的公式，匹配成功则将其添加到mergeFragment中
                if (mergeFragment == null) {
                    mergeFragment = Fragment.copyWithoutContent(fragment, true);
                }
                mergeFragment.setContent(mergeFragment.getContent() + content);

            }
            log.info("<=== 修改后: {}", JsonUtil.toJsonString(newFragments));
            itemContent.setFragments(newFragments);
        }
    }


}
